<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/static/layui-v2.6.8/layui/css/layui.css">
</head>
<style>
    .box {

        text-align: center;
        color: #808080;
    }

    /* .c-gray {
color: #ccc;
}

.c-green {
color: #16a840;
}

.c-red {
color: #dd4f43;
} */
    a {
        text-decoration: none;
        color: skyblue;
             
    }

    /* .layui-footer{
background-color: #23262e;
} */
    /* .tdo {
        background-color: #e0dcdc;
    } */
</style>

<body>
    <div class="layui-layout layui-layout-admin">
        <!-- 引入公共页面 -->
        {{include "./common/header.html" }}

        <!-- 引入公共页面 -->
        {{include "./common/side-menu.html" }}
        <div class="layui-body">
            <div style="padding: 15px;">
                <div class="layui-input-inline" style="display: flex;">
                    <input style="width: 200px;" class="layui-input" type="text" id="title" placeholder="输入文章标题进行搜索">
                    <select id="status" class="form-control" style="display: inline-block; width: 200px;">
                        <option value="">全部状态</option>
                        <option value="0">审核中</option>
                        <option value="1">通过</option>
                        <option value="2">失败</option>
                    </select>
                    <button class="layui-btn" id="search">搜索</button>
                </div>
                <table class="layui-table">
                    <colgroup>
                        <col width="50">
                        <col width="50">
                        <col width="50">
                        <col width="50">
                        <col width="50">
                        <col width="50">
                        <col width="170">
                        <col>
                        <col width="90">
                        <col width="300">
                    </colgroup>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>作者</th>
                            <th>标题</th>
                            <th>内容</th>
                            <th>分类</th>
                            <th>图片</th>
                            <th>链接</th>
                            <th>状态</th>
                            <th>添加时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="tbody"></tbody>
                </table>
                <div id="page"></div>
            </div>
        </div>

        {{include "./common/footer.html" }}
    </div>

</body>
<script src="https://momentjs.bootcss.com/downloads/moment.min.js"></script>
<script src="/static/js/jquery.js"></script>
<script src="/static/layui-v2.6.8/layui/layui.js"></script>
<script>

    // 初始化分页
    let curr = 1;
    let limit = 5;
    let laypage;
    let article;// 保存搜索的关键字
    let Audit_status;// 保存搜索的状态
    let isSearch = false;
    let statusTextMap = {
        0: '<span class="layui-bg-orange">待审核</span>',
        1: '<span class="layui-bg-green">审核通过</span>',
        2: '<span class="layui-bg-black">审核失败</span>'
    }

    // 发生ajax，获取分页的数据
    function getArticleData(curr, limit, callback, where = {}) {
        // 合并查询参数
        let params = Object.assign({ curr, limit }, where)
        $.get('/articleCount', params, function (res) {
            callback && callback(res)
        }, 'json');

    }

    // 渲染表格数据
    function renderTable(data) {
        let tbodyHtml = '';
        data.forEach((item, index) => {
            index = index + 1;
            let {
                id,
                article,
                content,
                cate_name,
                img,
                author,
                Audit_status,
                addtime,
                updata_time
            } = item;
            addtime = moment.unix(addtime).format("YYYY-MM-DD")
            updata_time = moment.unix(updata_time).format("YYYY-MM-DD")
            let copyItem = JSON.stringify(item);
            tbodyHtml += `<tr>
                            <td>${index}</td>
                            <td>${author}</td>
                            <td>${article}</td>
                            <td>${content}</td>
                            <td>${cate_name}</td>
                            <td><img src="/${img}" width="100px"></td>
                            <td>
                                <a href="/detail?id=${id}" class="layui-btn-primary layui-border-blue layui-btn layui-btn-sm">查看详情</a>
                                <button class="layui-btn layui-btn-sm showContent" data-item='${copyItem}'>查看全文</button>
                            </td>
                            <td> ${statusTextMap[Audit_status]}</td>
                            <td>${addtime}</td>
                            <td>
                                <a href="/edit?id=${id}" class="layui-btn  layui-btn-sm">编辑</a>
                                <a href="javascript:;" onclick="confirmDelete('${id}','${img}');"
                                 
                                <a href="/recycle?id=${id}" onclick="return confirm('确实加入回收站');"
                                    class="layui-btn  layui-btn-sm">加入回收站</a>
                                <a href="javascript:void(0)" onclick="ajaxDelete(this,'${id}','${img}')"
                                    class="layui-btn  layui-btn-sm">删除</a>
                            </td>
                        </tr>
        `;
        })
        return tbodyHtml;
    }

    // 渲染分页的结构
    function renderPage(laypage, ele, count, limit) {
        //执行一个laypage实例
        laypage.render({
            elem: ele,
            count, //数据总数，ajax,从服务端得到
            limit,
            jump: function (obj, first) {
                // first第一次触发为true,后面都是undefined
                let { curr, limit } = obj;
                // 如果是搜索，则取消默认请求
                if (isSearch) { return; }
                getArticleData(curr, limit, (res) => {
                    // 渲染表格
                    let tbody = renderTable(res.data)
                    $("tbody").html(tbody);
                }, { article, Audit_status })

            }
        });
    }

    layui.use('laypage', function () {
        laypage = layui.laypage;

        //请求完毕之后，在渲染分页
        // 加载分页数据和总记录数
        getArticleData(curr, limit, res => {
            let { count, data } = res;
            // 渲染分页结构
            renderPage(laypage, 'page', count, limit)
        })

    });

    //普通删除
    function confirmDelete(id, img) {
        layer.confirm('确认删除吗?确定吗?永久删除数据不可还原', {
            btn: ['是的', '取消'],
            shadeClose: true,
            shade: [0.3, '#000']

        }, () => {
            location.href = "/delete?id=" + id + "&img=" + img
        }, () => {
            layer.msg('已取消')
        });
    }

    // ajax异步删除
    function ajaxDelete(ele, id, img) {

        layer.confirm('确认删除吗', {
            btn: ['是的', '取消'], //按钮
            shadeClose: true,
            shade: [0.3, '#000']
        }, () => {
            //点了是的按钮触发
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState === 4 && this.status === 200) {
                    let data = JSON.parse(this.responseText);
                    let { code, message } = data;
                    if (code === 20000) {
                        // 删除成功,删除当前tr行
                        $(ele).parents('tr').remove()
                        setTimeout(function () {
                            layer.msg('删除成功', { icon: 1 })
                        }, 500)

                        layer.closeAll();
                    } else if (code === 30004) {
                        layer.msg(message)
                        location.href = "/login"
                    } else {
                        layer.msg('删除失败')
                    }
                }
            }
            xhr.open('post', '/ajaxdelete', true)
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
            xhr.send("id=" + id + "&img=" + img + "&flag=ajax")

        }, () => {
            layer.msg('否的')
        });
    }

    // 查看全文
    $("#tbody").on('click', '.showContent', function () {
        // alert(1)
        let data = JSON.parse($(this).attr('data-item'))
        let { article, content, author } = data;
        // 组装内容
        let htmlStr = `
        <div style="padding:10px;">
          <h2 style='text-align:center'>${article}</h2>
          <h2 style='text-align:center'>作者： ${author}</h2> 
          <p>${content}</p>
        <div>
      `;
        layer.open({
            type: 1,
            shadeClose: true,
            area: ['500px', '400px'], //宽高
            content: htmlStr
        });
    })

    //分页
    layui.use('laypage', function () {
        var laypage = layui.laypage;

        //执行一个laypage实例
        laypage.render({
            elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
            , count: 50 //数据总数，从服务端得到
        });
    });

    //  实现搜索功能
    $("#search").on('click', function () {
        title = $("#title").val();
        status = $("#status").val();
        // 发送搜索请求
        isSearch = true; // 说明点击了按钮
        getArticleData(curr, limit, function (res) {
            let { count, data } = res;
            // 重新渲染分页和表格数据
            renderPage(laypage, 'page', count, limit)
            isSearch = false;
            let tbody = renderTable(data)
            $("tbody").html(tbody);
        }, { title, status })
    })

    
</script>

</script>

</html>